<template>
  <div class="user-home" id="user-home">
    <div class="edit-banner" :style="{ height: editOpen ? '530px' : 0 }">
      <home-my :open="editOpen" :user="user" @change="init" />
    </div>
    <home-banner :user="user" @change="init" />
    <home-user :user="user" @follow-change="init" />
    <template v-if="state.userId && state.show">
      <home-list
        ref="homeRef"
        :user="user"
        :userId="state.userId"
        @change="init"
      />
    </template>
  </div>
</template>
<script setup lang="ts" name="UserPage">
//   import HomeMy from '@/views/userPage/view/HomeMy.vue'
import HomeBanner from './view/HomeBanner.vue'
import HomeUser from './view/HomeUser.vue'
import HomeList from './view/HomeList.vue'
import {
  ref,
  reactive,
  provide,
  onMounted,
  onActivated,
  nextTick,
  onBeforeMount
} from 'vue'
import userApi from '@/service/api/user'
import emitter from '@/common/mitt/bus.ts'
import { useKeep } from '@/hooks/useKeep'
import { getUrlParams } from '@/utils'
defineOptions({
  name: 'UserPage'
})
let routeParam: any = {}
const editOpen = ref(false)
interface stateInter {
  userId: number | null
  show: boolean
}
const state = reactive<stateInter>({
  userId: null,
  show: false
})
const user = ref<any>({
  id: 0
})
const openChange = () => {
  editOpen.value = !editOpen.value
}
provide('openChange', openChange)
const init = async (id: number | null = null) => {
  if (id) {
    state.show = false
    state.userId = id
  } else {
    state.userId = Number(routeParam.id)
  }
  const { data } = await userApi.otherUser({
    id: state.userId
  })
  user.value = data
  state.show = true
}
onActivated(() => {
  routeParam = getUrlParams()
  if (Number(routeParam.id) !== state.userId) {
    state.userId = null
    editOpen.value = false
    nextTick(() => {
      init()
    })
  }
})
const homeRef = ref()
onMounted(() => {
  routeParam = getUrlParams()
  init()
  // @ts-ignore
  emitter.on('idChange', (data: number) => {
    init(data)
  })
  emitter.on('userTabChange', () => {
    setTimeout(() => {
      homeRef.value?.typeChange()
    }, 100)
  })
})
onBeforeMount(() => {
  emitter.off('idChange')
  emitter.off('userTabChange')
})

/**
 * 保存页面滚动位置
 * */
useKeep()
</script>

<style scoped lang="scss">
.edit-banner {
  transition: height 0.3s;
  overflow: hidden;
}
</style>
